<?php

	namespace app\common\middleware;

	use app\event\ucenter\AuthGroup as AuthGroupEvent;
	use app\event\ucenter\User as UserEvent;
	use app\model\ucenter\User as UserModel;
	use app\event\ucenter\IpPool as IpPoolEvent;
	use think\exception\HttpResponseException;
	use think\facade\Config;
	use think\facade\Cookie;
	use think\facade\Env;
	use think\facade\Lang;
	use think\facade\Request;
	use think\facade\View;
	use think\Response;
	use think\response\Redirect;

	/**
	 * 权限检查
	 */
	class UserAuth
	{
		public function handle($request, \Closure $next)
		{
			$this->checkLogin($request, $request->user, $request->auth_module);
			$this->checkAuth($request, $request->user);
			return $next($request);
		}


		/**
		 * 检查权限.
		 * @param Request $request
		 * @param UserModel|null $user
		 * @param string $module
		 */
		protected function checkLogin($request, ?UserModel $user, string $module)
		{
			if (!$this->_needLogin($module, $request->controller(), $request->action())) {
				return true;
			} else {
				// 登陆检查
				// 未登陆进入登陆认证
				if (!$user) {
					// 缓存要登陆的模块
					Cookie::set('login_module', $module);
					if ($request->has('v')) {
						$url = url('/ucenter/login/' . $module);
						$html = '<title>404 页面不存在</title>
<div class="layui-fluid">
  <div class="layadmin-tips">
    <i class="layui-icon" face>&#xe664;</i>
    <div class="layui-text">
      <h2>
       <a href="' . $url . '">点我请重新登录</a>
      </h2>
    </div>
  </div>
</div>';
						$response = Response::create($html, 'html');
						throw new HttpResponseException($response);
					} else {

                        if ($module == 'admin')
                        {
                            $response = Response::create('请输入正确的登录地址', 'html');
                            throw new HttpResponseException($response);
                        }else if ($module !== 'index') {
							Cookie::set('login_redirect', '/' . $module);
							$response = Response::create('/ucenter/login/' . $module, 'redirect', 302);
							throw new HttpResponseException($response);
						} else {
							Cookie::set('login_redirect', $request->url(true));
							$response = Response::create('/signin', 'redirect', 302);
							throw new HttpResponseException($response);
						}
					}
				} else {
					$user['last_active_time'] = time_format();
					$user->isAutoWriteTimestamp(false)->save();
				}
			}
		}


		/**
		 * 检查权限
		 * @param Request $request
		 * @param UserModel|null $user
		 */
		public function checkAuth($request, ?UserModel $user)
		{
			if (false !== strpos(strtolower($request->pathinfo()), 'admin.')) {
				$module = 'admin';
			} else {
				$module =request()->auth_module;
			}
			if ($module == 'pay') {
				$module = 'merchant';
			}
			if (!$this->_needLogin($module, $request->controller(), $request->action())) {
				return true;
			} else{
				// 后台权限检查
				if ($module == 'admin') {
                    $controller = $request->controller();
                    if (str_contains($controller, '.')) {
                        $controller = str_replace('.', '/', $controller);
                    }
					$rule = $controller. '/' . $request->action();
					if (!AuthGroupEvent::checkRule($rule, $user)) {
						$type = $this->getResponseType($request);
						$header = [];
						$result = [];
						$result['message'] = '您没有当前权限，请更换其他账号';
						$result['module'] = request()->auth_module ;
						$result['login'] = (string)url('ucenter/logout/admin' );
						$result['code'] = 11002;
						if ($request->has('v')) {

							$html = '
<title>出错了</title>

<div class="layui-fluid">
  <div class="layadmin-tips">
    <i class="layui-icon" face>&#xe664;</i>
    
    <div class="layui-text" style="font-size: 20px;">
      '.$result['message'] .' <a href="'.$result['login'].'">退出</a>
    </div>    
  
    
  </div>
</div>';	$response = Response::create($html, 'html');
						}elseif ('html' == strtolower($type)) {
							$type = 'view';
							$html = app()->getRootPath() . 'app' . DIRECTORY_SEPARATOR . 'common' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'auth_error.html';
							$response = Response::create($html, $type)->assign($result)->header($header);
						} else {
							$response = Response::create($result, $type)->header($header);
						}
						throw new HttpResponseException($response);
					}

				}
			}



		}

		/**
		 *  检查是否要登录
		 * @param $module
		 * @param $controller
		 * @param $action
		 * @return bool
		 */
		private function _needLogin($module, $controller, $action): bool
		{
			if (in_array($module, Config::get('auth.auth_module'))) {
				return true;
			}
			$controllers = explode('.', $controller);
			if (count($controllers) == 2 && strtolower($controllers[0]) == 'admin') {
				return true;
			}
			return false;
		}

		/**
		 * 获取当前的response 输出类型
		 * @access protected
		 * @return string
		 */
		protected function getResponseType($request)
		{
			return $request->isJson() || $request->isAjax() ? 'json' : 'html';
		}

//		public function end(Response $response)
//		{
//			$module =request()->auth_module;
//		 $request = app('request');

//		}
	}